package xm.chengdu.com.sbglxt;

import java.lang.reflect.Method;
import java.util.ArrayList;

import utils.SpfUtils;
import utils.StringUtils;
import adapter.MyAdapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class PD_Activity extends Activity {
	MyAdapter lvAdapter;
	private BluetoothAdapter adapter;
	private Context mContext;
	Button button1;
	private ArrayList<BluetoothDevice> mainList = new ArrayList<BluetoothDevice>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pd_);
		ListView lv = (ListView) findViewById(R.id.main_lv);
		ImageView bt1 = (ImageView) findViewById(R.id.imageView1);
		button1 = (Button) findViewById(R.id.button1);
		button1.setVisibility(View.VISIBLE);
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				 
				adapter.cancelDiscovery();
				cxsm();
//				openView();
				mainList.clear();
				lvAdapter.clear();
				lvAdapter.notifyDataSetChanged();
				button1.setVisibility(View.INVISIBLE);

			}
		});
		bt1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				adapter.cancelDiscovery();
				finish();
			}
		});
		mContext = this;
//		openView();
		check();
		openBluetooth();
		lvAdapter = new MyAdapter();
		lv.setAdapter(lvAdapter);
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				adapter.cancelDiscovery();
				connectDevice(mainList.get(position));

			}
		});
	}

	private void check() {
		// 检查设备是否支持蓝牙      
		adapter = BluetoothAdapter.getDefaultAdapter();
		if (adapter == null) {
			Toast.makeText(mContext, "该设备不支持蓝牙", Toast.LENGTH_LONG).show();
		}

	}

	private void openBluetooth() {
		// 打开蓝牙   
		if (!adapter.isEnabled()) {
			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			// 设置蓝牙可见性，最多300秒   
			intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 10);
			mContext.startActivity(intent);
		}
		// 设置广播信息过滤   
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		// 注册广播接收器，接收并处理搜索结果   
		mContext.registerReceiver(receiver, intentFilter);
		// 寻找蓝牙设备，android会将查找到的设备以广播形式发出去   
		adapter.startDiscovery();
	}

	public void cxsm() {
		adapter.startDiscovery();
	}

	// 自定义广播类
	int i;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			 
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

				if (!mainList.contains(device)) {
					if (!StringUtils.isEmpty(device.getName())) {
//						if (device.getName().contains("HC")) {
							mainList.add(device);
							lvAdapter.addItem(device);
//							if (dialog != null) {
//								dialog.dismiss();
//								dialog = null;
//								i = 0;
//								adapter.cancelDiscovery();
//								button1.setVisibility(View.VISIBLE);
//							}
//							adapter.cancelDiscovery();
//						}

						//
						Log.e("BLUE", device.getName() + "__add");
					}

				}
				Log.e("BLUE", device.getName() + "__");
				// 搜索到的不是已经绑定的蓝牙设备
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					// 显示在TextView上

				}

			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
//				if (dialog != null) {
//					dialog.dismiss();
//					dialog = null;
//					button1.setVisibility(View.VISIBLE);
//				}
				button1.setVisibility(View.VISIBLE);
			} else {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device != null) {
					if (!mainList.contains(device)) {
						mainList.add(device);
						lvAdapter.addItem(device);
						Log.e("BLUE", device.getName() + "__add");
					}
				}
			}
			Log.e("BLUE", "size = " + mainList.size());

			lvAdapter.notifyDataSetChanged();
		}

	};

	protected void connectDevice(BluetoothDevice mBluetoothDevice) {
		try {
			// 连接建立之前的先配对
			if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
				Method creMethod = BluetoothDevice.class
						.getMethod("createBond");
				Log.e("TAG", "开始配对");
				creMethod.invoke(mBluetoothDevice);
				SpfUtils.put(PD_Activity.this, "address",
						mBluetoothDevice.getAddress());
			} else {
				removeBond(BluetoothDevice.class, mBluetoothDevice);
				Log.e("TAG", "配对失败" + mBluetoothDevice.getBondState() + "____"
						+ BluetoothDevice.BOND_NONE);
				SpfUtils.put(PD_Activity.this, "address", "");
			}
		} catch (Exception e) {

			Log.e("TAG", "配对失败");
			e.printStackTrace();
		}
	}

	/**
	 * 与设备解除配对 参考源码
	 */
	static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
			throws Exception {
		Method removeBondMethod = btClass.getMethod("removeBond");
		Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
		return returnValue.booleanValue();
	}

	ProgressDialog dialog = null;

	// 显示连接窗口
	public void openView() {
		dialog = new ProgressDialog(PD_Activity.this);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setTitle("扫描中........");
		dialog.setMessage("请稍后........");
		dialog.show();
		dialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
				switch (keyCode) {
				case KeyEvent.KEYCODE_HOME:
					if (dialog != null) {
						dialog.dismiss();
						dialog = null;
					}
					return true;
				}
				return false;
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}
}
